package org.zjvis.datascience.common.dto;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.util.ConstantUtil;

/**
 * @description 数据源信息表，数据驱动DTO
 * @date 2020-10-09
 */
@Data
public class DatabaseDTO extends BaseDTO {

    private Long id;

    private String name;

    private Integer type;

    private String configJson;

    private String description;

    public String schema() {
        String schema = null;
        JSONObject jsonObj = JSONObject.parseObject(configJson);
        String address = jsonObj.getString("address");
        int port = jsonObj.getIntValue("port");
        String db = jsonObj.getString("db");
        if (StringUtils.isEmpty(db)) {
            db = "";
        }

        if (ConstantUtil.DATASOURCE_TYPE_GREENPLUM == type) {
            schema = String.format("jdbc:pivotal:greenplum://%s:%s;DatabaseName=%s", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_MYSQL == type) {
            schema = String.format("jdbc:mysql://%s:%s/%s?characterEncoding=UTF-8", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_HIVE == type) {
//        schema = String.format("jdbc:presto://%s:%s/hive/%s", address, port, db);
            schema = String.format("jdbc:hive2://%s:%s/", address, port);
        } else if (ConstantUtil.DATASOURCE_TYPE_ELASTICSEARCH == type) {
            schema = String.format("jdbc:presto://%s:%s/elasticsearch/%s", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_TIDB == type) {
            schema = String.format("jdbc:presto://%s:%s/tidb/%s", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_SQLSERVER == type) {
            schema = String.format("jdbc:sqlserver://%s:%s", address, port);
            if (StringUtils.isNotEmpty(db)) {
                schema = schema + ";DatabaseName=" + db;
            }
        } else if (ConstantUtil.DATASOURCE_TYPE_ORACLE == type) {
            schema = String.format("jdbc:oracle:thin:@%s:%s/%s", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_HANA == type) {
            schema = String.format("jdbc:sap://%s:%s/%s?reconnect=true", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_DRUID == type) {
            schema = String.format("jdbc:avatica:remote:url=http://%s:%s/druid/v2/sql/avatica/", address, port);
        } else if (ConstantUtil.DATASOURCE_TYPE_CLICKHOUSE == type) {
            schema = String.format("jdbc:clickhouse://%s:%s/%s", address, port, db);
        } else if (ConstantUtil.DATASOURCE_TYPE_POSTGRES == type) {
            schema = String.format("jdbc:postgresql://%s:%s/%s", address, port, db);
        }

        return schema;
    }

}
